import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { PlayerService } from '../http/http-player.service';
import { Player } from '../http/player';

@Component({
    template: `
        <ul class="items">
            <li *ngFor="let player of players | async"
                [class.selected]="isSelected(player)"
                (click)="onSelect(player)">
                <span class="badge">{{ player._id }}</span> {{ player.name }}
            </li>
        </ul>
        <router-outlet></router-outlet>
    `
})
export class RouterListComponent implements OnInit {
    players: Observable<Player[]>;
    selectedId: string;
    constructor(private router: Router, private route: ActivatedRoute, private service: PlayerService, ) { }

    isSelected(player: Player) {
        return player._id === this.selectedId;
    }
    onSelect(player: Player) {
        this.selectedId = player._id;
        this.router.navigate(['detail/' + player._id], { relativeTo: this.route });
    }

    ngOnInit() {
        this.players = this.route.params.switchMap((params: Params) => {
            this.selectedId = params['id'];
            return this.service.getPlayers();
        });
    }
}